package com.uicole.push.server.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.uicole.push.server.dao.BaseDaoI;


@Repository("baseDao")
public class BaseDaoImpl<T,PK extends Serializable> implements BaseDaoI<T, PK> {
	protected final Log log = LogFactory.getLog(getClass());
	private SessionFactory sessionFactory;
	private HibernateTemplate hibernateTemplate;
	private Class<T> persistentClass;
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	public Serializable save(T o) {
		return this.getCurrentSession().save(o);
	}

	public void delete(T o) {
		this.getCurrentSession().delete(o);
	}

	public void update(T o) {
		this.getCurrentSession().update(o);
	}

	public void saveOrUpdate(T o) {
		this.getCurrentSession().saveOrUpdate(o);
	}

	public List<T> find(String hql) {
		return this.getCurrentSession().createQuery(hql).list();
	}
	
	public List<T> findSQL(String hql, Class T) {
		return this.getCurrentSession().createSQLQuery(hql).addEntity(T).list();
	}
	
	public List<T> findSQL(String hql) {
		return this.getCurrentSession().createSQLQuery(hql).list();
	}

	public List<T> find(String hql, Object[] param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.list();
	}

	public List<T> find(String hql, List<Object> param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return q.list();
	}

	public List<T> find(String hql, Object[] param, Integer page, Integer rows) {
		if (page == null || page < 1) {
			page = 1;
		}
		if (rows == null || rows < 1) {
			rows = 10;
		}
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
	}

	public List<T> find(String hql, List<Object> param, Integer page, Integer rows) {
		if (page == null || page < 1) {
			page = 1;
		}
		if (rows == null || rows < 1) {
			rows = 10;
		}
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
	}

	public T get(Class<T> c, Serializable id) {
		return (T) this.getCurrentSession().get(c, id);
	}

	public T get(String hql, Object[] param) {
		List<T> l = this.find(hql, param);
		if (l != null && l.size() > 0) {
			return l.get(0);
		} else {
			return null;
		}
	}

	public T get(String hql, List<Object> param) {
		List<T> l = this.find(hql, param);
		if (l != null && l.size() > 0) {
			return l.get(0);
		} else {
			return null;
		}
	}

	public Long count(String hql) {
		return (Long) this.getCurrentSession().createQuery(hql).uniqueResult();
	}

	public Long count(String hql, Object[] param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return (Long) q.uniqueResult();
	}

	public Long count(String hql, List<Object> param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return (Long) q.uniqueResult();
	}

	public Integer executeHql(String hql) {
		return this.getCurrentSession().createQuery(hql).executeUpdate();
	}

	public Integer executeHql(String hql, Object[] param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.executeUpdate();
	}

	public Integer executeHql(String hql, List<Object> param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return q.executeUpdate();
	}

	@Override
	public boolean exists(PK id) {
		Class persistentClass = getPersistentClass();
		T entity = (T) hibernateTemplate.get(persistentClass, id);
        return entity != null;
	}

	@Override
	public T get(PK id) {
		 T entity = (T) hibernateTemplate.get(getPersistentClass(), id);

	        if (entity == null) {
	            log.warn("Uh oh, '" + getPersistentClass() + "' object with id '" + id + "' not found...");
	            throw new ObjectRetrievalFailureException(getPersistentClass(), id);
	        }

	        return entity;
	}

	@Override
	public void remove(PK id) {
		hibernateTemplate.delete(this.get(id));
		
	}

	@Override
	public List<T> getAll() {
		return hibernateTemplate.loadAll(getPersistentClass());
	}

	public Class<T> getPersistentClass() {
		if(this.persistentClass==null){
			this.persistentClass = getType0();
		}
		return persistentClass;
	}

	private Class<T> getType0() {
		Class<? extends BaseDaoImpl> class1 = this.getClass();
		Type[] actualTypeArguments = dsfds(class1);
		Class<?> d = getClass().getSuperclass();
		
		return (Class<T>)actualTypeArguments[0];
	}

	private Type[] dsfds(Class class1) {
		Type type=class1.getGenericSuperclass();
		if(type instanceof ParameterizedType){//父亲有参数
			ParameterizedType parameterizedType=(ParameterizedType)type;
			Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
			if(actualTypeArguments!=null&&actualTypeArguments.length>0){
				return actualTypeArguments;
			}else if(class1!=Object.class){
				return dsfds(class1.getSuperclass());
			}else{
				throw new IllegalArgumentException("不存在泛形");
			}
		}else{
			return dsfds(class1.getSuperclass());
		}	
	}

}